const { getDbPool } = require('../infra/dbClient');
const db = getDbPool();

class DataPermissionModel {
  // 根据角色ID和权限类型获取数据权限
  static async getDataPermissionsByRoleId(roleId, permissionType = 'read') {
    const query = `
      SELECT dept_id FROM role_data_permission 
      WHERE role_id = ? AND permission_type = ?
    `;
    const [results] = await db.execute(query, [roleId, permissionType]);
    const deptIds = results.map(item => item.dept_id);
    
    return deptIds;
  }

  // 根据用户ID获取数据权限（考虑用户拥有的所有角色）
  static async getDataPermissionsByUserId(userId, permissionType = 'read') {
    const query = `
      SELECT DISTINCT rdp.dept_id 
      FROM role_data_permission rdp
      JOIN user_role ur ON rdp.role_id = ur.role_id
      WHERE ur.user_id = ? AND rdp.permission_type = ?
    `;
    const [results] = await db.execute(query, [userId, permissionType]);
    const deptIds = results.map(item => item.dept_id);
    
    return deptIds;
  }

  // 检查用户是否对特定部门有数据权限
  static async checkUserDeptPermission(userId, deptId, permissionType = 'read') {
    // 获取用户所有可访问的部门ID
    const accessibleDeptIds = await this.getDataPermissionsByUserId(userId, permissionType);
    
    // 检查目标部门ID是否在可访问列表中
    return accessibleDeptIds.includes(deptId);
  }

  // 分配角色数据权限
  static async assignDataPermissionsToRole(roleId, deptPermissions) {
    // deptPermissions 格式: [{ deptId, permissionType }]
    const connection = await db.getConnection();
    try {
      await connection.beginTransaction();

      // 删除原有数据权限
      await connection.execute('DELETE FROM role_data_permission WHERE role_id = ?', [roleId]);

      // 插入新数据权限
      if (deptPermissions && deptPermissions.length > 0) {
        const query = `
          INSERT INTO role_data_permission (role_id, dept_id, permission_type)
          VALUES ?
        `;
        const values = deptPermissions.map(item => [roleId, item.deptId, item.permissionType]);
        await connection.execute(query, [values]);
      }

      await connection.commit();

      // 移除了缓存清除操作
      
      return true;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  // 生成数据权限过滤条件
  static async generateDataPermissionFilter(userId, permissionType = 'read', fieldName = 'dept_id') {
    const accessibleDeptIds = await this.getDataPermissionsByUserId(userId, permissionType);
    
    if (!accessibleDeptIds || accessibleDeptIds.length === 0) {
      return `${fieldName} IS NULL`; // 无权限访问任何数据
    }
    
    return `${fieldName} IN (${accessibleDeptIds.map(id => '?').join(',')})`;
  }
}

module.exports = DataPermissionModel;